const device = wx.getSystemInfoSync();
Component({
  properties: {
    imageUrl: {
      type: String,
      observer: function (oldValue, newValue) {
        this.initImage().then(() => {
          this.initClip().then(() => {
            wx.hideLoading();
          })
        });
      }
    }
  },
  canvas: null, //绘图对象
  data: {
    clipCanvas: null,
    // 组件所需的参数
    lineInit: false, //画布初始化线
    arcInit: false, //画布初始化点
    device: device, //系统信息
    height: 300, //图片高度
    marginTop: 0, //图片顶部偏移
    marginLeft: 0, //图片左侧偏移
    imageUrl: '../../images/sf.jpg',
    ratio: 0.8, // 初始比例
    radius: 10, //四点半径
    clip: { //裁剪信息
      coordinate: {
        p1: [],
        p2: [],
        p3: [],
        p4: []
      }, //四点坐标
      sign: -1 //点击坐标 ，默认不点击
    }
  },
  methods: {
    initClip: function () {
      //初始化裁剪属性
      const that = this;
      return new Promise((reolve, reject) => {
        let initCoordiate = function () {
          //获取初始点坐标
          const w = that.data.width;
          const h = that.data.height;
          const x = (device.windowWidth - w) / 2;
          const y = that.data.marginTop;
          const coordinate = {
            p1: [x, y],
            p2: [x + w, y],
            p3: [x + w, y + h],
            p4: [x, y + h]
          };
          that.data.clip.coordinate = coordinate;
          that.data.clip.source = {
            p1: [x, y],
            p2: [x + w, y],
            p3: [x + w, y + h],
            p4: [x, y + h]
          };
        }
        //初始化坐标
        initCoordiate();
        that.canvas = wx.createCanvasContext('clip-canvas', this);
        that.createArc();
        that.createLine();
        reolve();
      })
    },
    createArc() {
      const coordinate = this.data.clip.coordinate;
      this.createLabel(coordinate.p1[0], coordinate.p1[1]);
      this.createLabel(coordinate.p2[0], coordinate.p2[1]);
      this.createLabel(coordinate.p3[0], coordinate.p3[1]);
      this.createLabel(coordinate.p4[0], coordinate.p4[1]);
    },
    createLabel(x, y) {
      this.canvas.beginPath();
      this.canvas.arc(x, y, this.data.radius, 0, 2 * Math.PI);
      this.canvas.setFillStyle('yellow');
      this.canvas.setStrokeStyle('yellow');
      this.canvas.fill();
      this.canvas.stroke();
      if (!this.arcInit) {
        this.arcInit = true;
        this.canvas.draw(true);
      }
    },
    createLine() {
      const coordinate = this.data.clip.coordinate;
      this.canvas.moveTo(coordinate.p1[0], coordinate.p1[1]);
      this.canvas.lineTo(coordinate.p2[0], coordinate.p2[1]);
      this.canvas.lineTo(coordinate.p3[0], coordinate.p3[1]);
      this.canvas.lineTo(coordinate.p4[0], coordinate.p4[1]);
      this.canvas.lineTo(coordinate.p1[0], coordinate.p1[1]);
      this.canvas.stroke();
      if (!this.lineInit) {
        this.lineInit = true;
        this.canvas.draw(true);
      }
    },
    initClipRegion(res) {
      //初始化裁剪区域
      // if (res.width > res.height) {
      return {
        width: device.windowWidth * this.data.ratio,
        height: res.height / (res.width / (device.windowWidth * this.data.ratio)),
        bl: res.width / (device.windowWidth * this.data.ratio)
      }
      // } else {
      //   return {
      //     height: device.windowHeight * this.data.ratio,
      //     width: res.width / (res.height / (device.windowHeight * this.data.ratio)),
      //     bl: res.height / (device.windowHeight * this.data.ratio)
      //   }
      // }
    },
    initImage() {
      //初始化图片属性
      let that = this;
      return new Promise((reolve, reject) => {
        wx.getImageInfo({
          src: this.data.imageUrl,
          complete: res => {
            let options = that.initClipRegion(res);
            console.log(options);
            options.cw = options.width;
            options.ch = options.height;
            options.marginTop = (device.windowHeight - options.height) / 2;
            options.marginLeft = (device.windowWidth - options.width) / 2;
            options.tw = res.width;
            options.th = res.height;
            that.setData(options);
            reolve();
          }
        })
      })
    },
    JudgeCoordinate: function (x, y) {
      //根据长按坐标判断为裁剪的那个点
      const coordinate = this.data.clip.coordinate;
      const that = this;
      [1, 2, 3, 4].forEach(val => {
        const point = coordinate['p' + val];
        if (x <= point[0] + 10 && x >= point[0] - 10 &&
          y <= point[1] + 10 && y >= point[1] - 10) {
          that.data.clip.sign = val;
          return; //运行结束
        }
      })
    },
    bindtouchstart: function (event) {
      const _this = this;
      if (this.data.isStart) {
        let touches = event.touches;
        if (touches.length == 0) return;
        const touche = touches[0];
        this.JudgeCoordinate(touche.x, touche.y);
      } else {
        setTimeout(() => {
          _this.data.isStart = true;
          let touches = event.touches;
          if (touches.length == 0) return;
          const touche = touches[0];
          _this.JudgeCoordinate(touche.x, touche.y);
        }, 300);
      }
    },
    bindtouchend: function (event) {
      //移动结束
      this.data.clip.sign = -1;
      this.data.isStart = false;
      const center = this.JudgeCenter();
      this.setData({
        cw: center.w,
        ch: center.h
      })
    },
    bindtouchmove: function (event) {
      let touches = event.touches;
      if (touches.length == 0) return;
      const touche = touches[0];
      const sign = this.data.clip.sign;

      this.data.clip.coordinate['p' + sign] = [touche.x, touche.y];
      this.canvas.draw(false);
      this.createArc();
      this.createLine();
      //计算四点中心点
    },
    JudgeCenter: function () {
      //计算中心坐标点
      const coordinate = this.data.clip.coordinate;
      //获取X轴最低点
      const x = coordinate.p1[0] < coordinate.p4[0] ? coordinate.p1[0] : coordinate.p4[0];
      //获取X轴最高点
      const _x = coordinate.p2[0] > coordinate.p3[0] ? coordinate.p2[0] : coordinate.p3[0];
      //获取Y轴最高点
      const y = coordinate.p1[1] < coordinate.p2[1] ? coordinate.p1[1] : coordinate.p2[1];
      //获取Y轴最低点
      const _y = coordinate.p3[1] > coordinate.p4[1] ? coordinate.p3[1] : coordinate.p4[1];

      const source = this.data.clip.source;

      //计算长度，计算高度
      const xy = _x - x; //宽度
      const _xy = _y - y; //高度
      const center = {
        x: x - this.data.marginLeft > 0 ? x - this.data.marginLeft : 0,
        y: y - this.data.marginTop > 0 ? y - this.data.marginTop : 0
      }
      return {
        x: xy / 2,
        y: _xy / 2,
        py: {
          x: x - source.p1[0],
          y: y - source.p1[1]
        },
        p: {
          x: center.x,
          y: center.y
        }, //初始点位
        w: xy,
        h: _xy
      }
    },

    cropperImg: function () {
      let that = this;
      const clipCanvas = wx.createCanvasContext('clipCanvas', this);
      //获取中心点坐标
      clipCanvas.save();
      const center = that.JudgeCenter();
      console.log('center', center);
      const coordinate = this.data.clip.coordinate;
      console.log('coordinate', coordinate);
      //移动中心点
      // clipCanvas.translate(center.x, center.y);

      //获取初始点


      //获取图片大小
      const width = this.data.width * this.data.bl;
      const height = this.data.height * this.data.bl;

      const ix = center.p.x * this.data.bl;
      const iy = center.p.y * this.data.bl;
      console.log(ix, iy,
        width, height,
        this.data.tw, this.data.th,
        this.data.width * this.data.bl, this.data.height * this.data.bl,
        this.data.tw, this.data.th);

      //画图
      clipCanvas.drawImage(that.data.imageUrl, ix, iy, width, height, 0, 0, this.data.width * this.data.bl, this.data.height * this.data.bl);
      clipCanvas.restore();
      clipCanvas.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: 'clipCanvas',
          fileType: 'jpg',
          destHeight: height,
          destWidth: width,
          success(response) {
            that.triggerEvent("getCropperImg", { url: response.tempFilePath })
          }
        }, that);
      })
    }
  }
})